
package org.jetnuke.dao.generic;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.jforum.JForumExecutionContext;
import net.jforum.dao.generic.AutoKeys;
import net.jforum.util.preferences.SystemGlobals;

import org.jetnuke.entities.ReviewsComments;

public class GenericReviewsCommentDAO extends AutoKeys implements
		org.jetnuke.dao.ReviewsCommentDAO {

	public int addNew(ReviewsComments rc) throws Exception {
		PreparedStatement p = this.getStatementForAutoKeys("ReviewCommentModel.addNew");
		this.setAutoGeneratedKeysQuery(SystemGlobals.getSql("ReviewCommentModel.lastGeneratedReviewCommentID"));
		initNewReviewComment(rc, p);
		
		int id = this.executeAutoKeysQuery(p);
				
		return id;
	}

	protected void initNewReviewComment(ReviewsComments rc, PreparedStatement p)throws Exception {
		p.setString(1,rc.getCOMMENTS());
		p.setTimestamp(2,new Timestamp(new Date().getTime()));
		p.setInt(3,rc.getRID());
		p.setInt(4,rc.getSCORE());
		p.setInt(5,rc.getUSERID());
		
	}
	public ReviewsComments selectByPk(int cid)throws Exception{
		PreparedStatement p = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("ReviewCommentModel.selectByPK"));
		p.setInt(1,cid);
		ResultSet rs = p.executeQuery();
		
		rs.next();
		ReviewsComments rc = new ReviewsComments();
		fillReviewsCommentsFromResultSet(rc,rs);			
		
		return rc;
	}

	public List selectByRID(int rid) throws Exception {
		PreparedStatement p = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("ReviewCommentModel.selectByRID"));
		p.setInt(1,rid);
		ResultSet rs = p.executeQuery();
		List list = this.processSelectAll(rs);
		rs.close();
		p.close();
		
		return list;
	}

	private List processSelectAll(ResultSet rs) throws Exception{
		List list = new ArrayList();
		while (rs.next()) {
			ReviewsComments u = new ReviewsComments();
			fillReviewsCommentsFromResultSet(u,rs);			
			list.add(u);
		}
		
		return list;
	}

	protected void fillReviewsCommentsFromResultSet(ReviewsComments rc, ResultSet rs) throws Exception{
		rc.setCID(rs.getInt("CID"));
		rc.setCOMMENTS(rs.getString("COMMENTS"));
		rc.setDATE(rs.getTimestamp("DATE"));
		rc.setRID(rs.getInt("RID"));
		rc.setSCORE(rs.getInt("SCORE"));
		rc.setUSERID(rs.getInt("USERID"));
	}

	public void deleteByRID(int rid) throws Exception {
		PreparedStatement p = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("ReviewCommentModel.deleteByRID"));
		p.setInt(1,rid);
		p.executeUpdate();
		p.close();
		
	}

	public void deleteByPK(int id) throws Exception {
		PreparedStatement p = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("ReviewCommentModel.deleteByPK"));
		p.setInt(1,id);
		p.executeUpdate();
		p.close();
		
	}

}
